package org.study.hibernate.test;


import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.criterion.CriteriaQuery;
import org.study.hibernate.entity.Person;

import java.util.List;

/**
 * Created by LUOLIANG on 2016/8/21.
 */
public class Main {
    private static SessionFactory sessionFactory;
    private static StandardServiceRegistry registry;

    static {
        registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        try {
            sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
        } catch (Exception e) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }

    public static void main(String[] args) {
        /****上面是配置准备，下面开始数据库操作******/
        Session session = getSession();

        System.out.println("start insert operation....");
        session.beginTransaction();
        Person person = new Person();
        person.setName("CodeMonkey");
        person.setSex("male");
        person.setAge(20);
        session.save(person);

        System.out.println("start select operation after insert....");
        List<Person> persons = session.createQuery("from Person").list();
        persons.forEach((p) -> System.out.println("result: " + p.toString()));

        Person person1 = persons.get(0);
        person1.setName("codeMonkey1");
        session.update(person);
        System.out.println("start select operation after update....");
        persons = session.createQuery("from Person").list();
        persons.forEach((p) -> System.out.println("result: " + p.toString()));

        session.delete(persons.get(0));

        System.out.println("start select operation after delete....");
        persons = session.createQuery("from Person").list();
        persons.forEach((p) -> System.out.println("result: " + p.toString()));

        session.getTransaction().commit();
        session.close();
    }
}
